package com.sais.manage.boot.building.asy;

import com.sais.common.utils.UUIDUtils;
import com.sais.manage.boot.building.dto.BuildingDTO;
import com.sais.manage.boot.building.dto.RoomBatchSaveDTO;
import com.sais.manage.boot.building.entity.Room;
import com.sais.manage.boot.building.exception.BuildingException;
import com.sais.manage.boot.building.mapper.RoomMapper;
import com.sais.manage.boot.daily.entity.Sanitation;
import com.sais.manage.boot.daily.mapper.SanitationMapper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 宿舍管理平台-异步创建房间类
 *
 * @author zwp
 * @date 2020/2/7
 */
@Component
public class AsyCreateRoom {

    @Resource
    private RoomMapper roomMapper;
    @Resource
    private SanitationMapper sanitationMapper;

    /**
     * 异步创建房间
     *
     * @param buildingDTO
     * @param roomBatchSaveDTO
     * @param layer            当前楼层
     */
    @Async(value = "asyncExecutor")
    public void createRoom(BuildingDTO buildingDTO, RoomBatchSaveDTO roomBatchSaveDTO, Integer layer) {
        String buildingCode = buildingDTO.getCode();
        String buildingName = buildingDTO.getName();
        String buildingId = buildingDTO.getUkId();

        Integer startNumber = roomBatchSaveDTO.getStartNumber();
        Integer count = roomBatchSaveDTO.getCount();
        String area = roomBatchSaveDTO.getArea();

        for (Integer i = startNumber; i <= count; i++) {
            if (i < 0 || i > 99) {
                throw new BuildingException(BuildingException.ROOM_NUM);
            }

            int roomNum;
            if (layer >= 10 && i >= 10) {
                roomNum = Integer.parseInt("" + layer + i);
            } else {
                roomNum = layer * 100 + i;
            }
            String roomName = buildingName + area + "区" + roomNum;
            String roomCode = buildingCode + "_" + area + roomNum;
            String roomId = UUIDUtils.getLower();
            Room room = Room.builder()
                    .ukId(roomId)
                    .name(roomName)
                    .code(roomCode)
                    .count(0)
                    .majorId("0")
                    .sort(roomNum)
                    .status(1)
                    .build();
            roomMapper.createRoom(room);
            roomMapper.bindBuildingRoom(buildingId, roomId);

            Sanitation sanitation = Sanitation.builder()
                    .content("无")
                    .ukId(UUIDUtils.getLower())
                    .roomId(roomId)
                    .score(Math.random() * 100)
                    .build();
            sanitationMapper.insert(sanitation);
        }
    }
}
